package com.yuwubao.hz_International.controllers.app;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.yuwubao.hz_International.entities.ConsumerEntity;
import com.yuwubao.hz_International.entities.GiftFans;
import com.yuwubao.hz_International.services.AppService;
import com.yuwubao.hz_International.services.ConsumerService;
import com.yuwubao.hz_International.util.Const;
import com.yuwubao.hz_International.util.MD5;
import com.yuwubao.hz_International.util.RestApiResponse;
import com.yuwubao.hz_International.util.SMSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

/**
 * Created by yangyu on 2018/1/25.
 */
@RestController
@RequestMapping("/app/consumer")
@Transactional
@CrossOrigin
@Api(value = "app接口")
public class ConsumerController {

    private final static Logger logger = LoggerFactory.getLogger(ConsumerController.class);

    @Autowired
    private ConsumerService consumerService;

    @Resource
    private AppService appService;

    /**
     * 发送短信验证码
     */
    @GetMapping("/getSMSCaptcha")
    @ApiOperation(value = "短信验证码")
    public RestApiResponse<String> getSMSCaptcha(@ApiParam(required = true, value = "手机号") @RequestParam String mobile) {
        RestApiResponse<String> result = new RestApiResponse<String>();
        try {
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            SendSmsResponse sendSmsResponse = SMSUtil.sendSms(mobile, verifyCode);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                result.successResponse(Const.SUCCESS, verifyCode, "获取验证码成功");
                return result;
            }
            result.failedApiResponse(Const.FAILED, "获取验证码失败");
        } catch (Exception e) {
            logger.warn("获取短信验证码异常", e);
            result.failedApiResponse(Const.FAILED, "获取短信验证码异常");
        }
        return result;
    }

    /**
     * 注册
     *
     * @param phone       注册的手机号
     * @param password    密码
     * @param invitePhone 邀请人手机号
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册接口")
    public RestApiResponse<ConsumerEntity> register(@ApiParam(required = true, value = "手机号") @RequestParam String phone,
                                                    @ApiParam(required = true, value = "密码") @RequestParam String password,
                                                    @ApiParam(value = "邀请人码") @RequestParam(required = false, defaultValue = "") String invitePhone) {
        RestApiResponse<ConsumerEntity> result = new RestApiResponse<ConsumerEntity>();
        try {
            ConsumerEntity consumerEntity = consumerService.findByPhone(phone);
            if (consumerEntity != null) {
                result.failedApiResponse(Const.FAILED, "该手机号已注册");
                return result;
            }
            ConsumerEntity invite = null;
            if (!"".equals(invitePhone)) {
                invite = consumerService.findByPhone(invitePhone);
                if (invite == null) {
                    result.failedApiResponse("邀请人不存在");
                    return result;
                }else {
                    //生成记录表
                    GiftFans fans = new GiftFans();
                    fans.setUserId(invite.getId());
                    fans.setPhone(phone);
                    fans.setTotalGift(new BigDecimal(0));
                    appService.createGiftFans(fans);
                }
            }
            ConsumerEntity createConsumerEntity = new ConsumerEntity();
            createConsumerEntity.setPhone(phone);
            createConsumerEntity.setName(phone);
            createConsumerEntity.setPassword(MD5.md5(password));
            createConsumerEntity.setCreateTime(new Date());
            createConsumerEntity.setInvitePhone(invitePhone);
            createConsumerEntity.setMoney(new BigDecimal("0"));
            createConsumerEntity.setGiftMoney(new BigDecimal("0"));
            createConsumerEntity.setWelfareMoney(new BigDecimal("0"));
            createConsumerEntity.setBonous(new BigDecimal("0"));
            createConsumerEntity.setWelfareYesterdayMoney(new BigDecimal("0"));
            createConsumerEntity.setWelfareProfitMoney(new BigDecimal("0"));
            ConsumerEntity entity = consumerService.save(createConsumerEntity);


            if (entity == null) {
                result.failedApiResponse(Const.FAILED, "注册失败,请稍后再试");
                return result;
            }
            result.successResponse(Const.SUCCESS, entity, "注册成功");
        } catch (Exception e) {
            logger.warn("注册异常", e);
            result.failedApiResponse(Const.FAILED, "注册异常");
        }
        return result;
    }

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登陆接口")
    public RestApiResponse<ConsumerEntity> login(@ApiParam(required = true, value = "手机号") @RequestParam String phone,
                                                 @ApiParam(required = true, value = "密码") @RequestParam String password) {
        RestApiResponse<ConsumerEntity> result = new RestApiResponse<ConsumerEntity>();
        try {
            ConsumerEntity consumerEntity = consumerService.findByPhone(phone);
            if (consumerEntity == null) {
                result.failedApiResponse(Const.FAILED, "您还未注册,请先注册");
                return result;
            }
            String pwd = MD5.md5(password);
            ConsumerEntity entity = consumerService.findByPhoneAndPassword(phone, pwd);
            if (entity == null) {
                result.failedApiResponse(Const.FAILED, "密码错误");
                return result;
            }
            result.successResponse(Const.SUCCESS, entity, "登录成功");
        } catch (Exception e) {
            logger.warn("登录异常", e);
            result.failedApiResponse(Const.FAILED, "登录异常");
        }
        return result;
    }


}
